public class ReversePairsDouble {
    // 升序
    int[] tmp1;
    public int reversePairs1(int[] nums) {
        int n = nums.length;
        tmp = new int[n];
        return mergeSort(nums, 0, n - 1);
    }

    public int mergeSort1(int[] nums, int left, int right) {
        if (left >= right) {
            return 0;
        }

        int ret = 0;
        // 1.根据中间点划分左右部分
        int mid = left + ((right - left) >> 1);
        // [left, mid] [mid+1, right]
        ret += mergeSort(nums, left, mid);
        ret += mergeSort(nums, mid + 1, right);

        // 2.统计逆序对个数
        int l = left, r = mid + 1;
        while (l <= mid && r <= right) {
            // 注意这里, 当两个指针其中一个遍历完了, 说明逆序对就统计完了
            // 不用再统计了, 就该去执行合并数组逻辑了
            if (nums[l] / 2.0 <= nums[r]) {
                l++;
            } else if(nums[l] / 2.0 > nums[r]) {
                ret += mid - l + 1;
                r++;
            }
        }

        // 3.合并两个有序数组
        int cur1 = left, cur2 = mid + 1, i = 0;
        while (cur1 <= mid && cur2 <= right) {
            if(nums[cur1] <= nums[cur2]) {
                tmp[i++] = nums[cur1++];
            }else {
                tmp[i++] = nums[cur2++];
            }
        }
        while (cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while (cur2 <= right) {
            tmp[i++] = nums[cur2++];
        }

        // 3.将辅助数组元素放回原数组中
        for (int j = 0; j < right - left + 1; j++) {
            nums[j + left] = tmp[j];
        }
        return ret;
    }

    // 降序
    int[] tmp;
    public int reversePairs(int[] nums) {
        int n = nums.length;
        tmp = new int[n];
        return mergeSort(nums, 0, n - 1);
    }

    public int mergeSort(int[] nums, int left, int right) {
        if (left >= right) {
            return 0;
        }

        int ret = 0;
        // 1.根据中间点划分左右部分
        int mid = left + ((right - left) >> 1);
        // [left, mid] [mid+1, right]
        ret += mergeSort(nums, left, mid);
        ret += mergeSort(nums, mid + 1, right);

        // 2.统计逆序对个数
        int l = left, r = mid + 1;
        while (l <= mid && r <= right) {
            if (nums[l] / 2.0 <= nums[r]) {
                r++;
            } else if(nums[l] / 2.0 > nums[r]) {
                ret += right - r + 1;
                l++;
            }
        }

        // 3.合并两个有序数组
        int cur1 = left, cur2 = mid + 1, i = 0;
        while (cur1 <= mid && cur2 <= right) {
            if(nums[cur1] <= nums[cur2]) {
                tmp[i++] = nums[cur2++];
            }else {
                tmp[i++] = nums[cur1++];
            }
        }
        while (cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while (cur2 <= right) {
            tmp[i++] = nums[cur2++];
        }

        // 3.将辅助数组元素放回原数组中
        for (int j = 0; j < right - left + 1; j++) {
            nums[j + left] = tmp[j];
        }
        return ret;
    }
}
